package leetcode_day._2021._202107._1120;

import java.util.*;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/7/18 10:09
 * 变位词组
 * 算法：排序 + 哈希表
 */
public class _18_面试题10_02 {
    public static void main(String[] args) {
        System.out.println(new _18_面试题10_02().groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        int n = strs.length;
        String[] clone = strs.clone();
        for (int i = 0; i < n; i++) {
            char[] chars = clone[i].toCharArray();
            Arrays.sort(chars);
            clone[i] = new String(chars);
        }
        Map<String, List<String>> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            List<String> list = map.getOrDefault(clone[i], new LinkedList<>());
            list.add(strs[i]);
            map.put(clone[i], list);
        }
        return new ArrayList<>(map.values());
    }

}
